<!-- 留言管理 - 弹框 -->
<template>
    <el-dialog 
    :title="typeTitle+'留言'"
    v-model="dialogVisible"
    width="45%"
    :close-on-click-modal="false" 
    :close-on-press-escape="true"
    @closed="resetForm(formRef)">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
            <el-form-item label="留言昵称" prop="nickname">
                <el-input v-model.trim="form.nickname" :readonly="billState || isreply" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item :label="isreply ? typeTitle+'邮箱': '留言邮箱'" prop="eMail">
                <el-input v-model.trim="form.eMail" :readonly="billState || isreply" placeholder="请输入留言邮箱"></el-input>
            </el-form-item>
            <el-form-item :label="isreply ? typeTitle+'内容': '留言内容'" prop="content">
                <el-input type="textarea" v-model="form.content" :readonly="billState" placeholder="请输入留言内容..."></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span>
                <el-button type="primary" class="" v-if="dialogState == 'add'" :loading="submitLoading" @click="submitClick">确定</el-button>
                <el-button type="primary" class="" v-if="dialogState == 'update'" :loading="updateLoading" @click="updateClick">确定</el-button>
                <el-button type="primary" class="" v-if="dialogState == 'reply'" :loading="replyLoading" @click="replyClick">确定</el-button>
                <el-button class="" @click="resetForm(formRef)">关闭</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { computed, nextTick, reactive, ref } from "vue";
import { messageApi } from '@/api/article/message/message-api';
import { ElMessage } from 'element-plus';


// ========================= 弹框控制 =========================
let dialogVisible = ref(false);
let dialogState = ref('add');
function onShowDialog(type, row) {
    if(row) {
        nextTick(() => {
            for(let key in form) {
                if(isreply.value && key == 'content') continue;
                form[key] = row[key];
            };
            form.id = row.id;
        })
    };
    dialogState.value = type;
    dialogVisible.value = true;
};

// 组件向外暴露属性或方法
defineExpose({
    onShowDialog
});

// ========================= 计算属性 =========================
const typeTitle = computed(() => {
    if(dialogState.value == 'add') return '新增';
    if(dialogState.value == 'update') return '修改';
    if(dialogState.value == 'view') return '查看';
    if(dialogState.value == 'reply') return '回复';
});

const billState = computed(() => {
    if(dialogState.value != 'view') return false;
    return true;
});

const isreply = computed(() => {
    if(dialogState.value == 'reply') return true;
    return false;
})

// ========================= 定义发射给父组件的方法 =========================
const emits = defineEmits(['updateMessageList']);

// ========================= 表单 =========================
const form = reactive({
    id:'',               // 主键
    userId:'',           // 留言用户
    nickname:'',         // 昵称
    eMail:'',            // 留言邮箱
    content:'',          // 留言内容
    status: false,       // 回复状态
    createdAt:'',        // 创建时间
    updatedAt:'',        // 更新时间
});

const rules = reactive({
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ],
    eMail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    content: [
        { required: true, message: '请输入留言内容', trigger: 'blur' }
    ],
});

// 表单操作
const formRef = ref();
let submitLoading = ref(false);
// 提交
function submitClick() {
    formRef.value.validate(async (vaild) => {
        try {
            if(vaild) {
                submitLoading.value = true;
                let date = new Date();
                form.createdAt = date;
                form.updatedAt = date;
                delete form.id;
                const res = await messageApi.create(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('新增成功');
                submitLoading.value = false;
                dialogVisible.value = false;
                emits('updateMessageList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            submitLoading.value = false;
        };
    });
};

// 更新
let updateLoading = ref(false);
function updateClick() {
    formRef.value.validate(async (vaild) => {
        try {
            if(vaild) {
                updateLoading.value = true;
                let date = new Date();
                form.updatedAt = date;
                const res = await messageApi.update(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('修改成功');
                updateLoading.value = false;
                dialogVisible.value = false;
                emits('updateMessageList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            updateLoading.value = false;
        };
    });
};

// 回复
let replyLoading = ref(false);
function replyClick() {
    formRef.value.validate(async (vaild) => {
        try {
            if(vaild) {
                replyLoading.value = true;
                let date = new Date();
                form.updatedAt = date;
                const res = await messageApi.replyMsg(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('回复成功');
                replyLoading.value = false;
                dialogVisible.value = false;
                emits('updateMessageList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            replyLoading.value = false;
        };
    });
};

// ========================= 重置表单 =========================
function resetForm(refFormName) {
    refFormName.resetFields(); // 重置表单
    for(let key in form) {
        form[key] = ''
    };
    form.status = false;
    dialogVisible.value = false;
};


</script>

<style lang="scss" scoped>

</style>
